﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;

namespace WNistnet
{
    public class Util
    {
        private static string result;
        //输入一个命令行，返回该命令行执行的结果
        //默认3000毫秒
        public static string GetCmdResult(string cmd)
        {
            return GetCmdResult(cmd, 3000);
        }

        /// <summary>
        /// 输入一个命令行，返回执行结果
        /// </summary>
        /// <param name="cmd">命令行</param>
        /// <param name="waitTime">命令执行等待时间</param>
        /// <returns></returns>
        public static string GetCmdResult(string cmd, int waitTime)
        {
            int defaultWaitTime = 3000;
            result = string.Empty;
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.UseShellExecute = false;
            process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);

            process.Start();
            process.BeginOutputReadLine();

            process.StandardInput.WriteLine(cmd);
            process.StandardInput.Flush();
            Thread.Sleep(defaultWaitTime);

            return result;
        }

        public static void process_OutputDataReceived(Object sender, DataReceivedEventArgs e)
        {
            result += e.Data;
        }
    }
}
